package com.youxuan.ssyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxuan.ssyx.acl.mapper.PermissionMapper;
import com.youxuan.ssyx.acl.service.PermissionService;
import com.youxuan.ssyx.acl.utils.PermissionHelper;
import com.youxuan.ssyx.model.acl.Permission;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuyang
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Override
    public List<Permission> queryAllPermission() {
        // 查询出所有的菜单
        List<Permission> allPermissionList = baseMapper.selectList(null);

        // 将查询到的所有菜单转换为标准的格式
        List<Permission> result = PermissionHelper.buildPermission(allPermissionList);
        return result;
    }

    @Override
    public void removeChildById(Long id) {
        // 存放所有要删除的菜单 id
        List<Long> idList = new ArrayList<>();

        // 根据当前菜单 id 获取下面的所有子菜单
        this.getAllPermissionId(id, idList);

        // 设置当前菜单 id
        idList.add(id);

        // 调用方法删除菜单
        baseMapper.deleteBatchIds(idList);
    }

    /**
     * 递归找当前菜单下面的所有子菜单
     * @param id {当前的菜单 id}
     * @param idList {当前菜单下的所有子菜单的 id}
     */
    private void getAllPermissionId(Long id, List<Long> idList) {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getPid,id);
        List<Permission> childList = baseMapper.selectList(wrapper);

        // 递归查询是否含有子菜单
        childList.stream().forEach(item -> {
            // 封装菜单 id 到 idList 集合中
            idList.add(item.getId());
            // 递归
            this.getAllPermissionId(item.getId(),idList);
        });
    }
}
